package com.itheima.app.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.itheima.domain.db.User;
import com.itheima.util.ConstantUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.Duration;

@Component
public class TokenInterceptor implements HandlerInterceptor {

    @Autowired
    StringRedisTemplate stringRedisTemplate;

    @Override
    //前置处理
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.获取token,判断token是否为空
        String token = request.getHeader("Authorization");

        //2.若不为空,从redis中获取用户数据
        if (StrUtil.isNotBlank(token)) {
            String userJson = stringRedisTemplate.opsForValue().get(ConstantUtil.USER_TOKEN + token);

            //3.判断用户数据
            if (StrUtil.isNotBlank(userJson)) {
                //4.若不为空,转成user
                User user = JSON.parseObject(userJson, User.class);

                if (user != null) {
                    //5.将user绑定到当前线程中
                    UserHolder.set(user);

                    //6.将redis中token续期一个月
                    stringRedisTemplate.opsForValue().set(ConstantUtil.USER_TOKEN+token,userJson, Duration.ofDays(30));

                    //7.放行
                    return true;
                }
            }
        }

        //8.若上面有一个判断不成立,返回401且不放行
        response.setStatus(401);
        return false;
    }

    @Override
    //后置处理
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //解绑
        UserHolder.remove();
    }
}
